import time, os

LEVEL_DEBUG = 1
LEVEL_INFO = 2
LEVEL_ERROR = 4
LEVEL_WARN = 3

LEVEL_DEFAULT = LEVEL_INFO
level = LEVEL_DEFAULT

base_dir = './logs'


def get_time(format: str):
    return time.strftime(format, time.localtime())


def get_file_name():
    files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]

    now = get_time("%Y-%m-%d")
    count = 1
    for file in files:
        if file.count(now) >= 1:
            count += 1

    return f"{now}-{count}"


file_name = get_file_name()
log_file = open(f"./logs/{file_name}.log", "w", encoding="UTF-8")
log_file_last = open(f"./logs/last.log", "w", encoding="UTF-8")
log_file_last.write(f"{file_name}\n")


def set_level(l):
    global level
    level = l


def send(msg):
    print(msg)
    log_file.write(f"{msg}\n")
    log_file_last.write(f"{msg}\n")


def info(msg):
    if LEVEL_INFO >= level:
        send(f"[{get_time("%H:%M:%S")}][INFO] {msg}")


def warn(msg):
    if LEVEL_WARN >= level:
        send(f"[{get_time("%H:%M:%S")}][WARN] {msg}")


def debug(msg):
    if LEVEL_DEBUG >= level:
        send(f"[{get_time("%H:%M:%S")}][DEBUG] {msg}")


def error(msg):
    if LEVEL_ERROR >= level:
        send(f"[{get_time("%H:%M:%S")}][ERROR] {msg}")


def close():
    log_file.close()
    log_file_last.close()
